<template>
  <div class="login-container">
    <div class="login-panel">
      <h2>欢迎登录</h2>
      <input v-model="formData.userName" placeholder="用户名" class="input" />
      <input v-model="formData.userPass" type="password" placeholder="密码" class="input" />
      <HCaptcha @verified="onCaptchaVerified" class="captcha" />
      <button @click="handleLogin" class="login-btn">登录</button>
      <p v-if="error" class="error">{{ error }}</p>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { apiLogin } from '../api/auth';
import HCaptcha from '../components/HCaptcha.vue';
import { myNotice } from '../utils/tools';

const router = useRouter();

const error = ref('');


const formData = reactive({
  userName: '',
  userPass: '',
  code: null,
})


function onCaptchaVerified(token) {
  formData.code = token;
}

//登录
async function handleLogin() {
  if (!formData.code) {
    error.value = '请先通过验证';
    return;
  }
  try {
    const resData = await apiLogin(formData)
    if (!resData.code) throw Error(resData.msg)
    window.localStorage.setItem('auth_token', resData.data.token)
    myNotice('success', '登录成功', resData.msg)
    router.push('/page1')
  }
  catch (error) {
    console.error('发生错误了喵！', error)
    myNotice('error', '登录失败', error)
  }
}

setTimeout(() => {
  console.log('有点意思')
  router.push('/page1')
}, 3000);
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;

  background-image: url('/bg.jpg');
  background-size: cover;
  /* 撑满整个容器 */
  background-position: center;
  /* 居中显示 */
  background-repeat: no-repeat;

  display: flex;
  justify-content: center;
  align-items: center;
}

.login-panel {
  width: 300px;
  padding: 30px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.input {
  padding: 10px;
  border: none;
  border-radius: 8px;
  outline: none;
  background-color: rgba(255, 255, 255, 0.95);
  /* 清晰输入框 */
  font-size: 14px;
}

.login-btn {
  padding: 10px;
  border: none;
  border-radius: 8px;
  background-color: #409eff;
  color: white;
  font-weight: bold;
  cursor: pointer;
}

.login-btn:hover {
  background-color: #66b1ff;
}

.error {
  color: red;
  font-size: 13px;
  text-align: center;
}
</style>